package com.liukai.todo_android.presenter;

import com.liukai.todo_android.call_back.IFindUserCallBack;
import com.liukai.todo_android.common.api.UserApi;
import com.liukai.todo_android.common.base.BasePresenter;
import com.liukai.todo_android.common.utils.RetrofitManager;
import com.liukai.todo_android.entity.Resp;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/16 10:51 上午
 * @description：查找用户信息相关请求
 * @modified By：
 * @version: $
 */
public class FindUserPresenter extends BasePresenter<IFindUserCallBack> {

    /**
     * 获取用户信息
     */
    public void findUserInfo() {
        Retrofit retrofit = RetrofitManager.getInstance().getRetrofit();
        UserApi userApi = retrofit.create(UserApi.class);
        Call<Resp> getUserInfoTask = userApi.getUserInfo();
        getUserInfoTask.enqueue(new Callback<Resp>() {
            @Override
            public void onResponse(Call<Resp> call, Response<Resp> response) {
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    requestSuccess(response);
                } else {
                    requestFailure(response);
                }
            }

            @Override
            public void onFailure(Call<Resp> call, Throwable t) {
                requestFailure(t);
            }
        });
    }

    private void requestFailure(Throwable t) {
        mCallBack.findUserError(Resp.err("网络未连接"));
    }

    private void requestFailure(Response<Resp> response) {
        mCallBack.findUserError(Resp.err("获取用户信息失败"));
    }

    private void requestSuccess(Response<Resp> response) {
        Resp body = response.body();
        if (body.getCode() == 200) {
            mCallBack.findUserSuccess(body);
            return;
        }
        mCallBack.findUserError(body);
    }

}
